package com.xindong.paking.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xindong.paking.dtos.IssueResult;
import com.xindong.paking.dtos.PageResult;
import com.xindong.paking.dtos.TbSpaceDTO;
import com.xindong.paking.dtos.TbSpaceListParams;
import com.xindong.paking.entity.ParkingLot;
import com.xindong.paking.entity.TbSpace;
import com.xindong.paking.exception.CustomerException;
import com.xindong.paking.mapper.ParkingLotMapper;
import com.xindong.paking.mapper.TbSpaceMapper;
import com.xindong.paking.service.TbSpaceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xindong.paking.utils.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wenbo
 * @since 2023-01-08
 */
@Service
public class TbSpaceServiceImpl extends ServiceImpl<TbSpaceMapper, TbSpace> implements TbSpaceService {

    @Autowired
    private TbSpaceMapper tbSpaceMapper;

    @Autowired
    private ParkingLotMapper parkingLotMapper;

    @Override
    public Result add(TbSpace tbSpace) {

        // 默认车位空闲
        tbSpace.setIsFree(0);

        // 添加车位
        tbSpaceMapper.insert(tbSpace);

        return Result.success("添加车位成功", null);
    }

    @Override
    public Result delete(Integer id) {

        tbSpaceMapper.deleteById(id);

        return Result.success("删除车位成功", null);
    }

    @Override
    public Result update(TbSpace tbSpace) {

        tbSpaceMapper.updateById(tbSpace);

        return Result.success("车位更新成功", null);
    }

    @Override
    public Result list(TbSpaceListParams params) {

        // 分页查询
        IPage<TbSpace> iPage = new Page<>(params.getPage(), params.getPageSize());

        QueryWrapper<TbSpace> wrapper = new QueryWrapper<>();

        // 将参数赋值到TbSpace当中
        TbSpace tbSpace = new TbSpace();
        BeanUtils.copyProperties(params, tbSpace);

        // 所有输入的参数都可以查询
        wrapper.setEntity(tbSpace);

        IPage<TbSpace> selectPage = tbSpaceMapper.selectPage(iPage, wrapper);

        // 获取停车场名字
        List<TbSpaceDTO> tbSpaceDTOS = new ArrayList<>();
        List<TbSpace> records = selectPage.getRecords();
        for (TbSpace record : records) {
            // 获取停车场名字
            TbSpaceDTO tbSpaceDTO = new TbSpaceDTO();
            BeanUtils.copyProperties(record, tbSpaceDTO);
            ParkingLot parkingLot = parkingLotMapper.selectById(record.getParkingId());
            tbSpaceDTO.setName(parkingLot.getName());
            tbSpaceDTOS.add(tbSpaceDTO);
        }

//        PageResult pageResult = new PageResult(selectPage.getRecords(), selectPage.getTotal(), params.getPage(), params.getPageSize());
        PageResult pageResult = new PageResult(tbSpaceDTOS, selectPage.getTotal(), params.getPage(), params.getPageSize());

        return Result.success("查询成功", pageResult);
    }

    @Override
    public Result warehousing(TbSpace tbSpace) {

        // 入库时间
        tbSpace.setStartTime(LocalDateTime.now());

        // 车位空闲状态
        tbSpace.setIsFree(1);

        int flag = tbSpaceMapper.updateById(tbSpace);

        if (flag == 0) {
            throw new CustomerException("入库失败");
        }

        return Result.success("入库成功", null);
    }

    @Override
    public Result issue(TbSpace tbSpace) {

        tbSpace = tbSpaceMapper.selectById(tbSpace.getId());

        // 没有该车位或没有车
        if (tbSpace == null || tbSpace.getIsFree() == 0) {
            throw new CustomerException("出库失败");
        }

        // 结束时间
        LocalDateTime endTime = LocalDateTime.now();
        // 计算一共停车时间
        long minutes = ChronoUnit.MINUTES.between(tbSpace.getStartTime(), endTime);

        // 下单

        // 将车位清空
        tbSpace.setIsFree(0);
        UpdateWrapper<TbSpace> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(TbSpace::getLicensePlateNumber, null) // 车牌号清空
                .set(TbSpace::getStartTime, null)   // 清空时间
                .eq(TbSpace::getId, tbSpace.getId()); // 根据id更新

        // 更新数据库
        //int flag = tbSpaceMapper.updateById(tbSpace);
        int flag = tbSpaceMapper.update(tbSpace, updateWrapper);

        if (flag == 0) {
            throw new CustomerException("出库失败");
        }

        // 获取停车时长、收费多少
        IssueResult result = new IssueResult(tbSpace.getLicensePlateNumber(),
                tbSpace.getStartTime(),
                endTime,
                minutes,
                0L
        );

        return Result.success("出库成功", result);
    }

    /**
     * 通过id查找
     * @param id
     * @return
     */
    @Override
    public Result selectById(Integer id) {
        TbSpace tbSpace = tbSpaceMapper.selectById(id);
        if (tbSpace == null) {
            throw new CustomerException("查询失败");
        }
        TbSpaceDTO tbSpaceDTO = new TbSpaceDTO();
        BeanUtils.copyProperties(tbSpace, tbSpaceDTO);
        ParkingLot parkingLot = parkingLotMapper.selectById(tbSpace.getParkingId());
        tbSpaceDTO.setName(parkingLot.getName());
        return Result.success("查询成功", tbSpaceDTO);
    }

    @Override
    public Result utilizationRate(Integer parkingId) {

        Double result = 0.0;

        // 为空判断全部的占有率
        if (parkingId == null) {
            // 总
            Double total = Double.parseDouble(tbSpaceMapper.selectCount(null).toString());

            // 当前不空闲的车位
            LambdaQueryWrapper<TbSpace> tbSpaceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tbSpaceLambdaQueryWrapper.eq(TbSpace::getIsFree, 1);
            Double notFree = Double.parseDouble(tbSpaceMapper.selectCount(tbSpaceLambdaQueryWrapper).toString());

            result = notFree / total;
        }else {
            // 总
            LambdaQueryWrapper<TbSpace> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TbSpace::getParkingId, parkingId);
            Double total = Double.parseDouble(tbSpaceMapper.selectCount(wrapper).toString());

            // 当前不空闲的车位
            LambdaQueryWrapper<TbSpace> tbSpaceLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tbSpaceLambdaQueryWrapper.eq(TbSpace::getIsFree, 1).eq(TbSpace::getParkingId, parkingId);
            Double notFree = Double.parseDouble(tbSpaceMapper.selectCount(tbSpaceLambdaQueryWrapper).toString());

            result = notFree / total;
        }

        return Result.success("获取成功！", result);
    }
}
